const app = getApp();
const util = require("util.js")
const storage = require("storage.js")
const constant = require("../constant.js")

function doCoachLogin(success, fail) {

  let that = this
  wx.checkSession({
    success: function () {
      try {
        var sessionResult = wx.getStorageSync(storage.keys.session)
        var openidResult = wx.getStorageSync(storage.keys.openid)
        if (sessionResult && openidResult && sessionResult != "" && openidResult != "") {
          console.log("登录中，storage也存在数据, 直接返回成功回调函数")
          typeof success == "function" && success(sessionResult, openidResult)
        } else {
          _doLogin(success, fail)
        }
      } catch (e) {
        console.log(e)
        console.log("登录中，storage不存在数据, 重新登录")
        _doLogin(success, fail);
      }
    },
    fail: function () {
      console.log("登录状态过期, 重新登录")
      _doLogin(success, fail);
    }
  })
}

function _doLogin(success, fail) {
  let that = this
  if(wx.qy) {
    wx.qy.login({
      success: function (res) {
        if (res.code) {
          console.log("小程序登录成功, 跳转到成功处理逻辑...")
          _handleCoachLoginSuccess(res, success, fail) // 发起成功回调
        } else {
          console.log("小程序登录失败, 跳转到失败处理逻辑...")
          _hanldeCoachLoginFail(res, fail)
        }
      },
      fail: function (res) {
        console.log("小程序登录失败, 跳转到失败处理逻辑...")
        console.log(res)
        _hanldeCoachLoginFail(res, fail)
      }
    })
  } else {
    wx.setStorageSync(storage.keys.mobile, constant.resource.test_mobile);
    typeof success == "function" && success()
    // typeof fail == "function" && fail("123")
  }
}

// 处理小程序登录成功
function _handleCoachLoginSuccess(res, success, fail) {

  console.log("小程序登录成功, 开始根据code [" + res.code + "]获取session与openid")
  wx.request({
    url: constant.api(app.globalData.pord).auth.prepare + res.code,
    method: 'GET',
    success: function (res) {

        console.log(res)

      if (res.data.code == "0") {
       
        var session = res.data.data.session_key;
        var userid = res.data.data.userid;
        var corpid = res.data.data.corpid;

        if(!corpid) {
          typeof fail == "function" && fail(res)
        }

        try {
          wx.setStorageSync(storage.keys.session, session)
          console.log("缓存session与openid成功，直接跳转到成功回调函数")
          _doSystemLogin(userid, success, fail);
        } catch (e) {
          console.log(e)
          typeof fail == "function" && fail(res)
          console.log("缓存session与openid失败: " + e)
        }
      } else {
        console.log("获取session与openid失败")
        console.log("request openid occurs error with code[" + res.data.code + "] message[" + res.data.message + "]")
      }
    },
    fail: function (response) {
      console.log("获取session与openid网络请求失败")
      console.log(response)
    }
  })
}

// 处理小程序登录失败
function _hanldeCoachLoginFail(res, fail) {
  console.log("直接返回失败回调函数")
  typeof fail == "function" && fail(res)
}

function _doSystemLogin(userid, success, fail) {
  console.log("corpid 获取成功, 开始根据corpid判断是否有登陆权限 [" + userid+ "]")
  wx.request({
    url: constant.api(app.globalData.pord).auth.login + userid,
    method: 'POST',
    success: function (res) {
      console.log(res);
      if (res.data.code == "0") {
        var principal = res.data.data.principal;
        console.log(principal)
        try {
          wx.setStorageSync(storage.keys.mobile, principal.mobile)
          typeof success == "function" && success(principal)
        } catch (e) {
          console.log(e)
          console.log("缓存session与openid失败: " + e)
        }
      } else {
        typeof fail == "function" && fail(res)
        console.log("暂无权限登录")
      }
    },
    fail: function (response) {
      console.log("获取session与openid网络请求失败")
      console.log(response)
      typeof fail == "function" && fail(res)
    }
  })
}

module.exports = {
  login: doCoachLogin
}
